package com.baidu.camera.ui;

import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.camera.R;
import com.baidu.camera.usbcamera.CameraViewInterface;
import com.baidu.camera.usbcamera.UVCCameraTextureView;
import com.baidu.camera.utils.FileUtils;
import com.baidu.camera.utils.ToastUtils;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.DeviceFilter;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;

import org.androidannotations.annotations.EActivity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

@EActivity
public class USBCamera3Activity extends AppCompatActivity implements View.OnClickListener {

    private com.baidu.camera.usbcamera.UVCCameraTextureView mCameraView;
    private android.widget.Button submit;
    //devices related
    private USBMonitor mUSBMonitor;
    private List<DeviceFilter> mFilter;
    private GoogleApiClient mGoogleApiClient;
    private UVCCamera mCamera;
    private Surface mSurface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera3);

        initView();
    }

    private void initView() {
       // buildGoogleApiClient();
        this.submit = (Button) findViewById(R.id.submit);
        this.submit.setOnClickListener(this);
        this.mCameraView = (UVCCameraTextureView) findViewById(R.id.mCameraView);
        //init usb monitor for finding usb devices
        mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);//init usb monitor
        mUSBMonitor.register();
        mFilter = DeviceFilter.getDeviceFilters(this, R.xml.device_filter);
        this.mCameraView.setCallback(mCallback);
    }

    @Override
    public void onClick(View v) {
        Bitmap bitmap = Bitmap.createBitmap(mCameraView.getBitmap());
        try {
            FileOutputStream os = new FileOutputStream(FileUtils.createImageFile(Environment.getExternalStorageDirectory() + "/img"));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private final USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
        @Override
        public void onAttach(final UsbDevice device) {
            Toast.makeText(getApplicationContext(), R.string.usbattached, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
            initCamera(ctrlBlock);
            startPreview();
        }

        @Override
        public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) {
            closeCamera();
        }

        @Override
        public void onDettach(final UsbDevice device) {
            Toast.makeText(getApplicationContext(), R.string.usbdetached, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
        }
    };



    private final CameraViewInterface.Callback mCallback = new CameraViewInterface.Callback() {
        @Override
        public void onSurfaceCreated() {

            if (!mUSBMonitor.isRegistered()) return;
            //Try to start camera
            final List<UsbDevice> list = mUSBMonitor.getDeviceList(mFilter.get(0));
            if (list.size() > 0) {
                UsbDevice device = list.get(0);
                ToastUtils.simpleToast(getApplicationContext(), device.getDeviceName());
                if (mUSBMonitor.hasPermission(device)) {
                    USBMonitor.UsbControlBlock ctrlBlock = new USBMonitor.UsbControlBlock(mUSBMonitor, device);
                    initCamera(ctrlBlock);
                    startPreview();
                } else {
                    mUSBMonitor.requestPermission(device);
                }
            } else {
                CameraDialog.showDialog(USBCamera3Activity.this);
            }
        }

    };


    //close camera
    private void closeCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.destroy();
            mCamera = null;
        }
    }


    //init open preview
    private void startPreview() {
        SurfaceTexture st = mCameraView.getSurfaceTexture();
//        if (mSurface != null) mSurface.release();
//        mSurface = new Surface(st);
        if (mCamera != null) {
            //mCamera.setPreviewSize(200, 200, UVCCamera.FRAME_FORMAT_MJPEG);
            //mCamera.setPreviewDisplay(mSurface);
            mCamera.setPreviewTexture(st);
            mCamera.startPreview();
        }
    }

    //init camera
    private void initCamera(USBMonitor.UsbControlBlock ctrlBlock) {
        mCamera = new UVCCamera();
        mCamera.open(ctrlBlock);
    }

}
